<template>
  <div>
    <div
        style="display: flex; justify-content: space-between; align-items: center; width: 100%; border-bottom: 2px solid #cccccc; padding-bottom: 10px">
      <span style="font-size: 17px; color: #333333; font-weight: bold">添加广告</span>
      <i class="el-icon-back" @click="handleBack()"
         style="font-size: 18px; color: deepskyblue; cursor: pointer;">返回</i>
    </div>
    <div style="margin-top: 20px;margin-left: 10px;width: 60%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="客户端" prop="isView" align="left">
          <el-radio-group v-model="ruleForm.isView">
            <el-radio :label="0" value="0">快递员</el-radio>
            <el-radio :label="1" value="1">会员端</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告标题" prop="adHeadline" align="left">
          <el-input v-model="ruleForm.adHeadline"></el-input>
        </el-form-item>
        <el-form-item label="广告图片" align="left">
          <div style="display: flex">
            <el-upload drag
                       class="avatar-uploader el-upload--text"
                       :action="uploadUrl"
                       :multiple="false"
                       :show-file-list="true"
                       :on-success="onImgChineseSuccess"
                       :before-upload="beforeUploadImage"
                       :on-error="onFileError"
            >
              <i v-if="ruleForm.picChinese" class="el-icon-view"></i>
              <i v-else class="el-icon-upload"></i>
              <div v-if="ruleForm.picChinese" style="width: 100%;height: 100%">
                <img :src="ruleForm.picChinese" class="avatar" style="width: 150px;height: 100%"/>
              </div>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传 JPEG/PNG/GIF/BMP/WebP 格式的图片，且不超过200MB
              </div>
            </el-upload>
            <el-upload drag
                       class="avatar-uploader el-upload--text"
                       :action="uploadUrl"
                       :multiple="false"
                       :show-file-list="true"
                       :on-success="onImgEnglishSuccess"
                       :before-upload="beforeUploadImage"
                       :on-error="onFileError"
            >
              <i v-if="ruleForm.picEnglish" class="el-icon-view"></i>
              <i v-else class="el-icon-upload"></i>
              <div v-if="ruleForm.picEnglish" style="width: 100%;height: 100%">
                <img :src="ruleForm.picEnglish" class="avatar" style="width: 150px;height: 100%"/>
              </div>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传 JPEG/PNG/GIF/BMP/WebP 格式的图片，且不超过200MB
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="跳转链接" prop="imgUrl" align="left">
          <el-input type="textarea" v-model="ruleForm.imgUrl"></el-input>
        </el-form-item>
        <el-form-item label="推送方式" prop="isType" align="left">
          <el-radio-group v-model="ruleForm.isType">
            <el-radio :label="0" value="0">即时推送</el-radio>
            <el-radio :label="1" value="1">定时推送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推送时间" prop="upDateTime" required align="left" v-if="this.ruleForm.isType === 1">
          <el-date-picker
              v-model="ruleForm.upDateTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
          <span style="color: #cccccc; margin-left: 10px;font-size: small">推送时间必须大于当前时间</span>
        </el-form-item>
        <el-form-item label="失效日期" required align="left" prop="downDateTime">
          <el-date-picker
              v-model="ruleForm.downDateTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
          <span style="color: #cccccc; margin-left: 10px;font-size: small">失效日期必须大于当前日期</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button @click="closeAddForm()">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
import {serverUrl} from "@/utils/request";
import {addAppAds} from "@/api/ad/appAds";

export default {
  name: "AddAppAd",
  data() {
    var validateUrl = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('跳转链接不能为空'));
      } else if (!/^(https?:\/\/)?([a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})+)(:[0-9]{1,5})?(\/[^\s]*)?$/.test(value)) {
        callback(new Error('请输入合法的URL地址'));
      } else {
        callback();
      }
    };
    return {
      uploadUrl: serverUrl + "/ad/oss/uploadOneFile",
      attrs: {
        accept: '*' //接受文件类型
      },
      file:{
        name: '',
        size: 0,
      },
      ruleForm: {
        adHeadline: '',
        picChinese: '',
        picEnglish: '',
        isType: '',
        upDateTime: '',
        downDateTime: '',
        isStatus: 2,
        createDateTime: '',
        bannerOrLandingpage: 0,
        imgUrl: '',
        isView: ''
      },
      bannerOrLandingpage:0,
      rules: {
        isView: [
          { required: true, message: '请选择客户端', trigger: 'change' }
        ],
        picEnglish: [
          { required: true, message: '请上传英文图片', trigger: 'change' }
        ],
        picChinese: [
          { required: true, message: '请上传中文图片', trigger: 'change' }
        ],
        adHeadline: [
          { required: true, message: '请输入广告标题', trigger: 'blur' },
          { min: 3, max: 40, message: '长度在 3 到 40 个字符', trigger: 'blur' }
        ],
        isType: [
          { required: true, message: '请选择推送方式', trigger: 'change' }
        ],
        upDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('推送时间不能为空'));
              }
              const currentTime = new Date();
              currentTime.setHours(currentTime.getHours() + 1); // 可以设置为当前时间之后的时间，这里示例为当前时间1小时后
              if (value < currentTime) {
                callback(new Error('推送时间必须大于当前时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        downDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('失效日期不能为空'));
              }
              const currentTime = new Date();
              currentTime.setDate(currentTime.getDate() + 1);
              if (value < currentTime) {
                callback(new Error('失效日期必须大于当前日期'));
              } else if(value < this.ruleForm.upDateTime) {
                callback(new Error('失效日期必须大于推送时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        imgUrl: [
          { validator: validateUrl, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    /*添加广告表单*/
    submitForm(formName) {
      if (this.ruleForm.picChinese === ''){
        this.$message({
          message: '中文图片不允许为空',
          type: 'warning'
        });
        return false;
      }
      if (this.ruleForm.picEnglish === ''){
        this.$message({
          message: '英文图片不允许为空',
          type: 'warning'
        });
        return false;
      }
      if (this.ruleForm.isType === 1 && this.ruleForm.upDateTime === ''){
        this.$message({
          message: '请选择推送时间',
          type: 'warning'
        });
        return false;
      }
      if (this.ruleForm.isType ===0 ){
        this.ruleForm.upDateTime = new Date();
      }
      this.ruleForm.createDateTime = new Date();
      if (this.ruleForm.upDateTime < new Date()){
        this.ruleForm.isStatus = 0;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.bannerOrLandingpage= this.bannerOrLandingpage;
          addAppAds(this.ruleForm).then(res => {
            if (res.code === 200){
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.resetForm('ruleForm');
              this.$router.go(-1);
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /*关闭页面*/
    closeAddForm(){
      this.resetForm('ruleForm');
      this.$router.go(-1);
    },
    /*清空表单*/
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /*返回按钮*/
    handleBack() {
      this.$router.go(-1);
    },
    /*上传失败*/
    onFileError(file) {
      console.log('error', file);
    },
    /*上传成功*/
    onImgChineseSuccess(response) {
      this.ruleForm.picChinese = response;
    },
    onImgEnglishSuccess(response) {
      this.ruleForm.picEnglish = response;
    },
    /*上传图片之前校验*/
    beforeUploadImage(file) {
      const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
      const isImage = validImageTypes.includes(file.type);
      if (!isImage) {
        this.$message.error('只能上传 JPEG/PNG/GIF/BMP/WebP 格式的图片!');
        return false;
      }
      // 校验文件大小，最大为200MB
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isLt200M) {
        this.$message.error('图片大小不能超过 200MB!');
        return false;
      }
      return true; // 通过校验
    }
  },
  mounted() {
    this.bannerOrLandingpage= this.$route.query.id;
  }
}
</script>

<style scoped>

</style>
